package com.ygqh.baby.handler;

import com.ygqh.baby.ao.BalanceType;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.OperationType;
import com.ygqh.baby.model.PrizeItem;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.YgCardCouponDetailService;
import com.ygqh.baby.service.YgCouponDetailService;
import com.ygqh.baby.service.YgUserBalanceDetailService;
import com.ygqh.baby.service.YgUserBalanceService;
import com.ygqh.baby.utils.DateConvertUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.ygqh.baby.utils.DrawPrizeUtil.lottery;

/**
 * @author: sunshuo
 * @date: 2018/12/17 17:07
 */
@Component
public class TurnTableHandler {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private RedisDao redisDao;
	@Autowired
	private YgCouponDetailService ygCouponDetailService;
	@Autowired
	private YgCardCouponDetailService ygCardCouponDetailService;
	@Autowired
	private YgUserBalanceService ygUserBalanceService;
	@Autowired
	private YgUserBalanceDetailService ygUserBalanceDetailService;

	public Object[] turnTable(Object[][] prizeArr, Integer defaultSelectId, String sourceKey, YgUser user, Date endDate) {
		Integer selectId;
		/*
		 * 随机一个奖项数
		 */
		List<Double> orignalRates = new ArrayList<>();
		for (Object[] aPrizeArr : prizeArr) {
			String str = (String) aPrizeArr[3];
			orignalRates.add(Double.valueOf(str));
		}
		selectId = lottery(orignalRates);
		/*
		 * 处理抽奖结果
		 */
		boolean isDefault = false;
		if (prizeArr[selectId][5] != null) {
			// 有总数量限制，需要验证已发总数量
			String value = redisDao.get(sourceKey + "_giveCount_" + prizeArr[selectId][0]);
			Integer totalCount = Integer.valueOf(prizeArr[selectId][5].toString());
			// 已发数量达到峰值
			if (StringUtils.isNotBlank(value) && Integer.valueOf(value).compareTo(totalCount) >= 0) {
				isDefault = true;
			}
		}
		if (!isDefault && prizeArr[selectId][6] != null) {
			// 有每日数量限制，需要验证当日已发数量
			String value = redisDao.get(sourceKey + "_giveCount_" + prizeArr[selectId][0]);
			Integer totalCount = Integer.valueOf(prizeArr[selectId][6].toString());
			// 当日已发数量达到峰值
			if (StringUtils.isNotBlank(value) && Integer.valueOf(value).compareTo(totalCount) >= 0) {
				isDefault = true;
			}
		}
		if (isDefault) {
			selectId = defaultSelectId;
		}
		PrizeItem.Type type = (PrizeItem.Type) prizeArr[selectId][4];
		switch (type) {
			case Balance:
				// 成长基金
				this.addBalance(user.getId(), new BigDecimal(prizeArr[selectId][1].toString()), sourceKey);
				break;
			case Coupon:
				// 优惠券
				Long couponId = Long.parseLong(prizeArr[selectId][1].toString());
				ygCouponDetailService.receiveCouponWithRemark(couponId, sourceKey, user);
				break;
			case Goods:
				// 实物
				Message message = ygCardCouponDetailService.generateCardCoupon(user.getId(), Long.parseLong(prizeArr[selectId][1].toString()), null, sourceKey);
				if (!Message.isSuccess(message)) {
					isDefault = true;
				}
				break;
			case Cash:
				// 暂无现金红包
			default:
				/*
				 *  默认赠予
				 */
				isDefault = true;
				break;
		}

		if (isDefault) {
			selectId = defaultSelectId;
			type = (PrizeItem.Type) prizeArr[selectId][4];
			if (PrizeItem.Type.Balance.equals(type)) {
				this.addBalance(user.getId(), new BigDecimal(prizeArr[selectId][1].toString()), sourceKey);
			} else if (PrizeItem.Type.Coupon.equals(type)) {
				ygCouponDetailService.receiveCouponWithRemark(Long.parseLong(prizeArr[selectId][1].toString()), sourceKey, user);
			}
		}
		if (prizeArr[selectId][5] != null) {
			// 有总数量限制， 更新已领取总数量
			String key = sourceKey + "_giveCount_" + prizeArr[selectId][0];
			String value = redisDao.get(key);
			if (StringUtils.isNotBlank(value)) {
				value = (Integer.valueOf(value) + 1) + "";
			} else {
				value = "1";
			}
			long expire = DateConvertUtils.addDay(endDate, 1).getTime();
			redisDao.set(key, value, expire);
			logger.info(sourceKey + "：【" + prizeArr[selectId][2].toString() + "】已被领取" + value + "个");
		}
		if (prizeArr[selectId][6] != null) {
			// 有每日数量限制， 更新已领取每日数量
			String key = sourceKey + "_giveCount_" + prizeArr[selectId][0];
			String value = redisDao.get(key);
			if (StringUtils.isNotBlank(value)) {
				value = (Integer.valueOf(value) + 1) + "";
			} else {
				value = "1";
			}
			redisDao.set(key, value, 24 * 60 * 60 * 1000);
			logger.info(sourceKey + "：【" + prizeArr[selectId][2].toString() + "】今日已被领取" + value + "个");
		}
		return prizeArr[selectId];
	}

	private void addBalance(Long userId, BigDecimal money, String remark) {
		ygUserBalanceService.backAcountPrice(userId, money);
		ygUserBalanceDetailService.addBalanceDetail(userId, money, BalanceType.Balance, OperationType.Activity, remark);
	}

}
